<template>
  <div class="login-container">
    <el-form ref="ruleFormRef" :model="form" class="login-form" :rules="rules">
      <div>
        <h3 class="title">管理后台</h3>
      </div>
      <el-form-item class="form-item" prop="name">
        <el-input v-model="form.name" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item class="form-item" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入登录密码" />
      </el-form-item>
      <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click="handleLogin(ruleFormRef)">登 录</el-button>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { ElForm } from 'element-plus'
import { OauthLogin } from '@/service/common'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

const store = useStore()
type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()
const router = useRouter()

interface IForm {
  name: string //登录名
  password: string //密码
}
interface IRules {
  name: Array<any> //登录名
  password: Array<any> //密码
}

const loading = ref<boolean>(false)
const form = reactive<IForm>({
  name: '',
  password: ''
})
const rules = reactive<IRules>({
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }]
})

const handleLogin = (formEl: FormInstance | undefined): void => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      OauthLogin(form).then((res: any) => {
        if (res.success) {
          store.commit('SET_TOKEN', res.data)
          store.dispatch('getMenus').then((menures: any) => {
            router.push('/home')
          })
        }
      })
    }
  })
}
</script>
<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #2d3a4b;
  overflow: hidden;
  text-align: center;
  color: #fff;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
}
</style>
